<?php

namespace app\admin\controller\qingdongams\customer;
use addons\qingdongams\model\Field;
use addons\qingdongams\model\File;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\RecordRead;
use addons\qingdongams\model\Remind;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\User;
use app\admin\controller\qingdongams\Base;
use addons\qingdongams\model\Contacts;
use addons\qingdongams\model\Comment;
use addons\qingdongams\model\Record as RecordModel;
use app\admin\model\qingdongams\Jigou;
use think\DB;
use think\Exception;

/**
 * 客户跟进记录
 */
class Record extends Base {
    protected $relationSearch = true;

    public function _initialize() {
        parent::_initialize();
        $this->model = new RecordModel();
    }

    /**
     * 客户跟进记录
     */
    public function index() {

        $need = input('need','','trim');
        $customer_id = input('customer_id','','trim');
        $contacts_id = input('contacts_id','','trim');
        $leads_id = input('leads_id','','trim');
        $contract_id = input('contract_id','','trim');
        $busniess_id = input('busniess_id','','trim');
        //0:全部 1：我负责的 2：下属负责的 3：今日待跟进 4:今日已跟进
        $type = input('type',0);
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            switch($type){
                case 1:
                    $staff = Staff::info();
                    $wheres['record.create_staff_id'] =  $staff->id;
                    break;
                case 2:
                    $wheres['record.create_staff_id'] =  array('in',Staff::getLowerStaffId());
                    break;
                case 3:
                    $start = date('Y-m-d 00:00:00');
                    $end = date('Y-m-d 23:59:59');
                    $record = RecordModel::where(array('relation_type'=>1,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select();
                    $relationId = [];
                    foreach($record as $k=>$v){
//                        $whereRe['id'] = array('gt',$v['relation_id']);
                        $whereRe['relation_id'] = $v['relation_id'];
                        $recordData = RecordModel::where($whereRe)->count();
                        if($recordData == 0){
                            $relationId[] = $v['id'];
                        }

                    }
                    $wheres['record.id'] =  array('in',$relationId);
                    $staff = Staff::info();
                    $wheres['record.create_staff_id'] =  $staff->id;
                    break;
                case 4:
                    $start = date('Y-m-d 00:00:00');
                    $end = date('Y-m-d 23:59:59');
                    $record = RecordModel::where(array('relation_type'=>1,'createtime'=>array(array('egt',strtotime($start)),array('elt',strtotime($end)))))->field("id,relation_id")->select();
                    $relationId = [];
                    foreach($record as $k=>$v){
//                        $whereRe['id'] = array('gt',$v['relation_id']);
                        $whereRe['relation_id'] = $v['relation_id'];
                        $recordData = RecordModel::where($whereRe)->count();
                        if($recordData >=1){
                            $relationId[] = $v['id'];
                        }

                    }
                    $wheres['record.id'] =  array('in',$relationId);
                    $staff = Staff::info();
                    $wheres['record.create_staff_id'] =  $staff->id;
                    break;
                default:
                    $wheres['record.create_staff_id'] =  array('in',Staff::getMyStaffIds());
                    break;

            }

            $wheres['record.relation_type'] = 1;
            $wheres['record.follow_type'] = ['neq','其它'];
            if(isset($need) && $need =='customer'){
                $staff = Staff::info();
                $wheres['record.create_staff_id'] =  $staff->id;
                $wheres['record.status'] = 0;
                $wheres['record.next_time'] = array(array('egt',date('Y-m-d 00:00:00')),array('lt',date('Y-m-d 23:59:59')));
                $customerlist = $this->model->where($wheres)->column('relation_id');
                if($customerlist){
                    $whereExit['relation_id'] = array('in',$customerlist);
                    $whereExit['next_time'] = array('gt',date('Y-m-d 23:59:59'));
                    $recordIds = $this->model->where($whereExit)->column('id');
                    if($recordIds){
                        $wheres['record.id'] = array('in',$recordIds);
                    }
                }
            }
            if(isset($need) && $need =='contacts'){
                $staff = Staff::info();
                $wheres['create_staff_id'] =  $staff->id;
                $wheres['record.status'] = 0;
                $wheres['record.relation_type'] = 2;
                $wheres['record.next_time'] = array(array('egt',date('Y-m-d 00:00:00')),array('lt',date('Y-m-d 23:59:59')));
                $customerlist = $this->model->where($wheres)->column('relation_id');
                if($customerlist){
                    $whereExit['relation_id'] = array('in',$customerlist);
                    $whereExit['next_time'] = array('gt',date('Y-m-d 23:59:59'));
                    $recordIds = $this->model->where($whereExit)->column('id');
                    if($recordIds){
                        $wheres['record.id'] = array('in',$recordIds);
                    }
                }
            }
            if(isset($customer_id) && $customer_id){
                $wheres['record.relation_type'] = 1;
                $wheres['record.relation_id'] = $customer_id;
                unset($wheres['record.create_staff_id']);
            }
            if(isset($contacts_id) && $contacts_id){
                $wheres['record.relation_type'] = 2;
                $wheres['record.relation_id'] = $contacts_id;
                unset($wheres['record.create_staff_id']);
            }
            if(isset($leads_id) && $leads_id){
                $wheres['record.relation_type'] = 4;
                $wheres['record.relation_id'] = $leads_id;
                unset($wheres['record.create_staff_id']);

            }
            if(isset($contract_id) && $contract_id){
                $wheres['record.relation_type'] = 3;
                $wheres['record.relation_id'] = $contract_id;
                unset($wheres['record.create_staff_id']);
            }
            if(isset($busniess_id) && $busniess_id){
                $wheres['record.relation_type'] = 5;
                $wheres['record.relation_id'] = $busniess_id;
                unset($wheres['record.create_staff_id']);
            }

//            $sql = $this->model->where($where)->where($wheres)->with(['staff','customer'])->where("customer.customer_type", "机构")->order($sort, $order)->buildSql();
            $list   = $this->model->alias("record")->where($where)->where($wheres)->field("record.*")->order($sort, $order);
            $list   = $list->paginate($limit);

            foreach($list as $k=>$v){
                if(!isset($v['customer']) || !$v['customer']){
                    $v['customer'] = array('id'=>'','name'=>'');
                }
                $v['staff'] = Staff::where("id", $v["create_staff_id"])->field("name")->find();
                if(isset($v['customer']) && $v['customer']){
                    $username =  User::where("id", $v['customer']["user_id"])->value("name");
                    $temp = [];
                    $temp["name"] = $username;
                    $v["user"] = $temp;

                    $username =  Jigou::where("id", $v['customer']["jigou_id"])->value("jigou_name");
                    $temp = [];
                    $temp["jigou_name"] = $username;
                    $v["jigou"] = $temp;
                }
            }
            $row    = $list->items();
            $result = array("total" => $list->total(), "rows" => $row, "sql" => $this->model->getLastSql());


            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 添加跟进
     */
    public function add($ids = null) {
        $relation_type=input('relation_type',1);
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            // 表单验证
            if (($result = $this->qingdongamsValidate($params, 'Record', 'create')) !== true) {
                $this->error($result);
            }

            if(!empty($params['files'])){
                $params['files']=File::getId($params['files']);
            }
            $reminds_id = $this->request->post('reminds_id/a');
            $params['reminds_id']='';
            if($reminds_id){
                $params['reminds_id'] = implode(',',$reminds_id);
            }

            Db::startTrans();
            try {
                $result = $this->model::createRecord($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result) {
                $this->success('创建跟进记录成功');
            }
            $this->error('创建失败');
        }

        $follow= Field::getField('客户状态');
        $customer=Customer::getList();
        $customers = [];
        foreach($customer as $k=>$v){
            $customers[$v['id']] = $v['name'];
        }
        if($relation_type == 2){
            $contacts=Contacts::where(['id'=>$ids])->column('id,name');
            $this->assign('contacts',$contacts);
        }

        $customer_info = Customer::where("id", $ids)->find();
        if($customer_info){
            $follow_value = $customer_info["follow"];
        }else{
            $follow_value = "";
        }

        $remind=Remind::where(['type'=>Remind::RECORD_TYPE])->find();
        $staff_ids=$remind['staff_ids']??'';
        $this->assign('staff_ids', $staff_ids);
        $this->assign('ids', $ids);
        $this->assign('relation_type', $relation_type);
        $this->assign('customer', $customers);
        $this->assign('follow', $follow);
        $this->assign('follow_value', $follow_value);
        $this->assign('staff', Staff::where([])->column('name','id'));
        return $this->view->fetch();
    }
    /**
     * 跟进详情
     */
    public function detail($ids = null) {
        $row = $this->model->with(['staff','file'])->where([
            'id' => $ids,
        ])->find();
        if (empty($row)) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
        if($row['staff_id']){
            $createname = Staff::where(['id'=>$row['staff_id']])->value('name');
        }else{
            $createname = isset($row['staff']['name']) ?  $row['staff']['name'] : '';
        }
        //标记通知已读
        Message::setRead(Message::RECORD_TYPE, $ids, $this->_staff->id);
        //添加阅读记录
        RecordRead::addRead($ids, $this->_staff->id);
        $row['createname'] = $createname;
        $this->assign('row', $row);
        $this->assignconfig("idinfo", ['id' => $ids]);
        return $this->view->fetch();
    }
    /**
     * 评论
     */
    public function comment() {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $record_id = input('record_id','');
            $wheres['relation_id'] = $record_id;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list   = Comment::where($where)->where($wheres)->with(['staff','record'])->order("id", $order)->paginate($limit);
            $row    = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
//            echo var_dump($result);
//            die();
        }

        return $this->view->fetch();
    }

}